<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { useUserStore } from '@vben/stores';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { customerAdd, customerInfo, customerUpdate } from '#/api/hm/customer';
import { familyList } from '#/api/hm/family';
import { productList } from '#/api/hm/product';
import { deptList } from '#/api/system/dept';

import { modalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const userStore = useUserStore();

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-1',
    // 默认label宽度 px
    labelWidth: 100,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await customerInfo(id);
      await formApi.setValues(record);
    }

    modalApi.modalLoading(false);
  },
});
const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
  return hasAccessByRoles(['admin', 'superadmin', 'ceo']);
});
async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    // 提交时默认给当前登录人的deptId和userId
    // data.staffId = isAdmin.value ? data.staffId : userStore.userInfo?.userId;
    data.storeId = isAdmin.value ? data.storeId : userStore.userInfo?.deptId;
    await (isUpdate.value ? customerUpdate(data) : customerAdd(data));
    emit('reload');
    await handleCancel();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

// 获取服务店铺列表
onMounted(async () => {
  const requestParams = { ancestors: '101', deptCategory: 'DP' };
  const deptTree = await deptList(requestParams);
  const deptOptions = [];
  const deptTransOptions = deptTree.map((item) => ({
    label: item.deptName,
    value: item.deptId.toString(),
  }));
  deptOptions.push(...deptTransOptions);
  // 选中后显示在输入框的值 即父节点 / 子节点
  // addFullName(deptTree, 'label', ' / ');
  formApi.updateSchema([
    {
      fieldName: 'storeId',
      componentProps: {
        // fieldNames: { label: 'label', value: 'id' },
        options: deptOptions,
        showSearch: true,
        optionFilterProp: 'label',

        defaultValue: userStore.userInfo?.deptId,
      },
    },
  ]);
});

// 获取产品列表
onMounted(async () => {
  const ret = await productList({
    pageNum: 1,
    pageSize: 999,
    status: '0',
    productType: 'CP',
  });
  const dataSourceOptions = [];
  const transOptions = ret.rows.map((item) => ({
    label: item.productName,
    value: item.productId.toString(),
  }));
  dataSourceOptions.push(...transOptions);
  formApi.updateSchema([
    {
      fieldName: 'takingProducts',
      componentProps: {
        options: dataSourceOptions,
      },
    },
  ]);
});
// 获取家庭组列表
onMounted(async () => {
  const ret = await familyList({
    pageNum: 1,
    pageSize: 999,
  });
  const dataSourceOptions = [];
  const transOptions = ret.rows.map((item) => ({
    label: item.familyName,
    value: item.familyId.toString(),
  }));
  dataSourceOptions.push(...transOptions);
  formApi.updateSchema([
    {
      fieldName: 'familyId',
      componentProps: {
        options: dataSourceOptions,
      },
    },
  ]);
});

async function handleCancel() {
  modalApi.close();
  await formApi.resetForm();
}
</script>

<template>
  <BasicModal :close-on-click-modal="false" :title="title" class="w-[900px]">
    <BasicForm />
  </BasicModal>
</template>
